﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MgSoft.Excel.Util
{
    public static class SheetColumnNameUtil
    {

        public static string ColumnIndexToColumnName(int index)

        {

            index = index + 1;

            int system = 26;

            char[] digArray = new char[100];

            int i = 0;

            while (index > 0)

            {

                int mod = index % system;

                if (mod == 0)

                    mod = system;

                digArray[i++] = (char)(mod - 1 + 'A');

                index = (index - 1) / 26;

            }

            StringBuilder sb = new StringBuilder(i);

            for (int j = i - 1; j >= 0; j--)

            {

                sb.Append(digArray[j]);

            }

            return sb.ToString();

        }

        public static int ColumnNameToColumnIndex(string columnName)

        {

            var index = 0;

            char[] chars = columnName.ToUpper().ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                index += (chars[i] - 'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
            }

            return index-1;//从0开始计数

        }
    }
}
